﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Primitives;
using System.IO;

namespace XOS_VHD_Tools.VHD
{
    public abstract class VHDFSDriver : IVHDFSDriver
    {
        public abstract bool Initialize(VHDPartition partition);

        private static readonly ComposablePart[] _parts;

        static VHDFSDriver()
        {
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in the same assembly as the Program class
            catalog.Catalogs.Add(new DirectoryCatalog(Path.GetDirectoryName(typeof(App).Assembly.Location), "XOS_VHD_*.dll"));

            //Create the CompositionContainer with the parts in the catalog
            var _container = new CompositionContainer(catalog);

            _parts = catalog.Parts.Select(t => t.CreatePart()).ToArray();
        }

        public abstract IDirectory RootDirectory { get; }

        public static IVHDFSDriver GetDriver(VHDPartition part)
        {
            var drivers = new List<IVHDFSDriver>();
            foreach (var cp in _parts)
            {
                var items = cp.ExportDefinitions.Select(t => cp.GetExportedValue(t));

                var drv = items.Cast<IVHDFSDriver>().Where(t => t.Initialize(part)).FirstOrDefault();

                if (drv != null)
                {
                    return drv;
                }
            }

            return null;

        }

        public virtual void Format(VHDPartition partition)
        {
            throw new NotSupportedException();
        }

        public virtual object Clone()
        {
            return MemberwiseClone();
        }
    }
}
